package com.aishua.fire.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.aishua.fire.common.RequestInterfaceUtil;
import com.aishua.fire.config.init.Init;
import com.aishua.fire.mapper.dto.AccteamList;
import com.aishua.fire.entity.ateam.AddAccountteamInfo;
import com.aishua.fire.entity.ateam.UpdAccountteamInfo;
import com.aishua.fire.entity.ateam.UpdateAccountteamInfo;
import com.aishua.fire.jpa.AccountAccountteamDao;
import com.aishua.fire.jpa.AccountteamDao;
import com.aishua.fire.jpa.AccountteamPermteamDao;
import com.aishua.fire.jpa.entity.AccountAccountteam;
import com.aishua.fire.jpa.entity.AccountAccountteamId;
import com.aishua.fire.jpa.entity.Accountteam;
import com.aishua.fire.jpa.entity.AccountteamPermteam;
import com.aishua.fire.jpa.entity.AccountteamPermteamId;
import com.aishua.fire.jpa.entity.Permteam;
import com.aishua.fire.mapper.AccountMapper;
import com.aishua.fire.mapper.AccountteamMapper;
import com.aishua.fire.mapper.AccountteamPermteamMapper;
import com.aishua.fire.mapper.PermteamMapper;
import com.aishua.fire.mapper.dto.AteamPermTeamSearchDto;
import com.aishua.fire.mapper.dto.PermteamAllowedDto;
import com.aishua.fire.service.AccountteamService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AccountteamServiceImpl implements AccountteamService {

	@Autowired
	private AccountteamDao accountteamDao;
	
	@Autowired
	private AccountAccountteamDao accountAteamDao;
	
	@Autowired
	private AccountteamPermteamDao accountteamPermteamDao;
	
	@Autowired
	private AccountteamMapper accountteamMapper;
	
	@Autowired
	private AccountMapper accountMapper;
	
	@Autowired
	private RequestInterfaceUtil requestUtil;
	
	@Autowired
	private AccountteamPermteamMapper AtteamPteamMapper;
	
	@Autowired
	private PermteamMapper permteamMapper;
	
	@Autowired
	private Init init;
	
	//增
	@Transactional
	public void add(AddAccountteamInfo roleInfo) {
		//新增账户组表
		Accountteam accountteam = new Accountteam();
		accountteam.setAccountteamName(roleInfo.getAccountteamName());
		accountteam.setAccountteamDesc(roleInfo.getAccountteamDesc());
		accountteam.setCreateDate(new Date());
		accountteamDao.save(accountteam);
		//新增账户组-权限组表
		List<AccountteamPermteam> list=new ArrayList<>();
		List<String> permteamId = roleInfo.getPermteamId();
		for (String id : permteamId) {
			AccountteamPermteam ap = new AccountteamPermteam();
			ap.setAccountteamPermteamId(new AccountteamPermteamId(accountteam.getAccountteamId(),Long.parseLong(id)));
			ap.setAuthType(roleInfo.getAuthType());
			ap.setCreateDate(new Date());
			list.add(ap);
		}
		accountteamPermteamDao.save(list);
		
		//添加账户组权限缓存
		init.addAccountteam(accountteam.getAccountteamId());
	}

	//删除账户组+账户组权限组
	@Transactional
	public void delete(String accountteamId) {
		//删除账户组权限缓存
		init.delAccountteam(Long.parseLong(accountteamId));
		
		//删除账户组
		accountteamDao.delete(Long.parseLong(accountteamId));
		//删除账户组权限组
		AtteamPteamMapper.deleteAteamPteam(accountteamId);
		
		
	}

	//改
	@Override
	public void update(UpdateAccountteamInfo updateRole) {
		Accountteam accountteam = accountteamDao.findOne(Long.parseLong(updateRole.getAteamId()));
		accountteam.setAccountteamId(Long.parseLong(updateRole.getAteamId()));
		accountteam.setAccountteamName(updateRole.getAteamName());
		accountteam.setAccountteamDesc(updateRole.getAteamDesc());
		accountteamDao.saveAndFlush(accountteam);
	}

	/**
	 * 查看详情
	 */
	@Override
	public Accountteam findRoleId(String roleId) {
		return accountteamDao.findOne(Long.parseLong(roleId));
	}

	/**
	 * 条件列表查询
	 */
	@Override
	public List<AteamPermTeamSearchDto> searchList(String accountteamName) {
		List<AteamPermTeamSearchDto> accountteamList = accountteamMapper.getAccountteamList(accountteamName);
		
		for(AteamPermTeamSearchDto ateamPermTeamSearchDto:accountteamList) {
			//获取权限组列表
			List<PermteamAllowedDto> allowedPermteams = accountteamMapper.getPermteamListByAteamId(ateamPermTeamSearchDto.getAccountteamId());
			ateamPermTeamSearchDto.setAllowedPermteams(allowedPermteams);
			
		}
		
		
		
		return accountteamList;
		
	}

	/**
	 * 通过账户获取账户组列表
	 */
	@Override
	public List<Accountteam> getAteamListByAccountId(final String accountId) {
		
		final List<AccountAccountteam> accountAteamList = accountAteamDao.findAll(new Specification<AccountAccountteam>() {
            
			@Override
            public Predicate toPredicate(Root<AccountAccountteam> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<AccountAccountteamId> userNamePath = root.get("accountAccountteamId");
                //连接查询条件, 不定参数，可以连接0..N个查询条件
                query.where(cb.equal(userNamePath.get("accountId").as(Long.class), accountId)); //这里可以设置任意条查询条件
                return null;
            }
        });
		
		if(accountAteamList !=null && accountAteamList.size() > 0) {
			final List<Long> ateamIds = new ArrayList<>();
			for(int i = 0;i<accountAteamList.size();i++) {
				ateamIds.add(accountAteamList.get(i).getAccountAccountteamId().getAccountteamId());
			}
			
			log.info("accountAteamList的值是:{}",accountAteamList);
			return accountteamDao.findAll(new Specification<Accountteam>() {
	            
				@Override
	            public Predicate toPredicate(Root<Accountteam> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
					//CriteriaQuery<Accountteam> criteriaQuery = cb .createQuery(Accountteam.class);
					//Root<Accountteam> accountteamPath = criteriaQuery.from(Accountteam.class);
					//accountteamPath.in(accountAteamList);
					
					query.where(root.get("accountteamId").in(ateamIds));
	                return null;
	            }
	        });
		}else {
			return new ArrayList<Accountteam>();
		}
		
		
	}

	
	@Override
	public void testDelete(String ateamName, String ateamDesc) {
		Accountteam accountteam = accountteamDao.findByAccountteamName("test2");
		log.info("账户组信息:{}",accountteam);
		
		accountteamDao.deleteByAccountteamNameAndAccountteamDesc(ateamName, ateamDesc);
	}

	//全查Accountteam表
	public List<Accountteam> getAccountteamList() {
		return accountteamDao.findAll();
	}

	//通过账户组id找到对应的账户信息
	public List<AccteamList> findAccountByaccountteamId(Long ateamId) {
		Map<String, Object> pram=new HashMap<>();
		pram.put("ateamId", ateamId);
		pram.put("status", 0);
		List<AccteamList> accountList = accountMapper.findAccountByaccountteamId(pram);
		return accountList;
	}

	//通过账户id找到对应的账户组信息
	public List<Accountteam> findByaccountId(Long accountId) {
		List<Accountteam> accountteams = accountteamDao.findByaccountId(accountId);
		return accountteams;
	}

	//通过账户id找到所有对应的账户组信息map
	public Map<String, Object> findByAccountIdMap(Long accountId) {
		//先根据id查询账户信息
		Map<String, Object> pram=new HashMap<>();
		pram.put("loginId", accountId);
		AccteamList accteamLists = accountMapper.findAccountById(pram);
		//再根据账户id找到对应的账户组信息
		List<Accountteam> accountteams = findByaccountId(accountId);
		Map<String, Object> map=new HashMap<>();
		map.put("account", accteamLists);
		map.put("accountteams", accountteams);
		return map;
	}
	
	@Override
	public  List<Accountteam> getAttList(){
	    return	accountteamDao.getAccList();
		
	}

	//获取账户组id和name
	public List<Accountteam> findIdAndName() {
		List<Accountteam> accountteams = accountteamMapper.findIdAndName();
		return accountteams;
	}

	//查询账户组表的name和id(过滤后)
	public List<Accountteam> findFilterIdAndName(Long accountId) {
		List<Accountteam> accountteams = accountteamMapper.findFilterIdAndName(accountId);
		return accountteams;
	}

	//修改用户组+账户权限组
	@Transactional
	public void updateAteam(UpdAccountteamInfo upd) {
		//修改账户组
		Accountteam accountteam=accountteamDao.findOne(Long.parseLong(upd.getAccountteamId()));
		accountteam.setAccountteamName(upd.getAccountteamName());
		accountteam.setAccountteamDesc(upd.getAccountteamDesc());
		accountteamDao.saveAndFlush(accountteam);
		List<String> permteamId = upd.getPermteamId();
		if (permteamId!=null && permteamId.size() !=0) {//代表修改时,选中了权限组
			//删除账户组-权限组表
			AtteamPteamMapper.deleteAteamPteam(upd.getAccountteamId());
			//添加账户组-权限组表
			List<AccountteamPermteam> list=new ArrayList<>();
			
			for (String id : permteamId) {
				AccountteamPermteam ap = new AccountteamPermteam();
				ap.setAccountteamPermteamId(new AccountteamPermteamId(accountteam.getAccountteamId(),Long.parseLong(id)));
				ap.setAuthType(upd.getAuthType());
				ap.setCreateDate(new Date());
				list.add(ap);
			}
			accountteamPermteamDao.save(list);
		}
		
	}

	//过滤后的id和name
	public List<Permteam> findIdAndNameGuoLv(String accountteamId) {
		return permteamMapper.findIdAndNameGuoLv(accountteamId);
	}

}
